/**
 * 从网络获取书籍信息控制器 
 * controller/fetch.js
 */
 
const express = require("express");
const axios = require("axios").default;
const cheerio = require("cheerio");
 
const util = require("../common/util");
const config = require("../common/config");
 
//设置axios访问server的user-agent
const axiosConfig = {
  headers: {
    "User-Agent":
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.34",
  },
};	
//书籍信息的结构
let bookInfo = {
  title: "", //书名
  pic: "", //图片
  author: "", //作者
  publisher: "", //出版社
  producer: "", //出品方
  subtitle: "", //副标题
  originalTitle: "", //原作名
  translator: "", //译者
  pubdate: "", //出版年
  pages: "", //页数
  price: "", //价格
  binding: "", //装帧
  series: "", //丛书
  isbn: "", //isbn
  intro: "", //内容简介
  doubanId: "", //豆瓣ID
};
 
/**
 * 从豆瓣获取书籍信息
 * @param {express.Request} req
 * @param {express.Response} res
 */
function fetchFromDouban(req, res) {
  let isbn = req.params.isbn; //获取路由参数中的isb值
 
  let doubanUrl = config.douban.baseUrl + isbn;
  axios
    .get(doubanUrl, axiosConfig)
    .then((result) => {
      clearBookInfo();
      bookInfo.doubanId = result.request.path.split("/")[2]; //获取豆瓣ID‘
      //   util.log(result.data);
      parseDoubanBook(result.data);
      res.json(util.FormatJSONData(200, "从豆瓣获取书籍信息成功", bookInfo));
    })
    .catch((error) => {
      util.err(error);
      res.json(
        util.FormatJSONData(400, "从豆瓣获取书籍信息失败", { error: error })
      );
    });
}
 
/**
 * 分析豆瓣读书的书籍页面信息
 *
 * @param {String} html - html内容
 */
function parseDoubanBook(html) {
  const $ = cheerio.load(html);
 
  let title = $("#wrapper h1 span").html();
  //   util.log(title);
  let pic = $("#wrapper #content #mainpic img").attr("src");
  //   util.log(pic);
  let info = $("#wrapper #content #info").text().trim();
  //   util.log(info);
  let intro = $("#wrapper #content .related_info #link-report .intro")
    .text()
    .trim()
    .replace(/\s+/g, "\n");
  //   util.log(intro);
 
  bookInfo.title = title;
  bookInfo.pic = pic;
  bookInfo.intro = intro;
  formatInfo(info);
}
 
/**
 * 豆瓣书籍中的·info·信息提取
 *
 * @param {String} info - info信息
 */
function formatInfo(info) {
  let infoArr = [];
  info = info.split("\n");
  info.forEach((element) => {
    element = element.trim();
    if (!element.match(/^[ ]*$/)) {
      infoArr.push(element);
    }
  });
 
  let infoStr = infoArr.join("");
  let temp = infoStr
    .replace("作者:", "作者:")
    .replace("出版社:", "|出版社:")
    .replace("原作名:", "|原作名:")
    .replace("副标题:", "|副标题:")
    .replace("出品方:", "|出品方:")
    .replace("译者:", "|译者:")
    .replace("出版年:", "|出版年:")
    .replace("页数:", "|页数:")
    .replace("定价:", "|定价:")
    .replace("装帧:", "|装帧:")
    .replace("丛书:", "|丛书:")
    .replace("ISBN:", "|ISBN:");
  // util.log(temp);
  let infoC = temp.split("|");
  for (let i = 0; i < infoC.length; i++) {
    const element = infoC[i];
    if (element.match("作者")) {
      bookInfo.author = element.split(":")[1].trim();
    }
    if (element.match("出版社")) {
      bookInfo.publisher = element.split(":")[1].trim();
    }
    if (element.match("原作名")) {
      bookInfo.originalTitle = element.split(":")[1].trim();
    }
    if (element.match("副标题")) {
      bookInfo.subtitle = element.split(":")[1].trim();
    }
    if (element.match("出品方")) {
      bookInfo.producer = element.split(":")[1].trim();
    }
    if (element.match("译者")) {
      bookInfo.translator = element.split(":")[1].trim();
    }
    if (element.match("出版年")) {
      bookInfo.pubdate = element.split(":")[1].trim();
    }
    if (element.match("页数")) {
      bookInfo.pages = element.split(":")[1].trim();
    }
    if (element.match("定价")) {
      bookInfo.price = element.split(":")[1].trim();
    }
    if (element.match("装帧")) {
      bookInfo.binding = element.split(":")[1].trim();
    }
    if (element.match("丛书")) {
      bookInfo.series = element.split(":")[1].trim();
    }
    if (element.match("ISBN")) {
      bookInfo.isbn = element.split(":")[1].trim();
    }
  }
}
 
/**
 * 清除全局bookInfo中的原有内容
 */
function clearBookInfo() {
  for (const key in bookInfo) {
    if (Object.hasOwnProperty.call(bookInfo, key)) {
      bookInfo[key] = "";
    }
  }
} 
 
module.exports = {
  fetchFromDouban,
};